package com.hulu73.struts1.core;

import java.io.Serializable;
import java.util.Enumeration;
import java.util.Properties;

public abstract class BaseConfig implements Serializable {
	
	protected boolean configured = false;
	
	private Properties properties = new Properties();

	public void freeze() {
        configured = true;
    }
	
	public void throwIfConfigured() {
        if (configured) {
            throw new IllegalStateException("Configuration is frozen");
        }
    }
	
	public void setProperty(String key, String value) {
        throwIfConfigured();
        properties.setProperty(key, value);
    }
	
	public String getProperty(String key) {
        return properties.getProperty(key);
    }
	
	 protected Properties getProperties() {
	        return this.properties;
	 }
	 
	 protected void setProperties(Properties properties) {
	        this.properties = properties;
	 }
	 
	 protected void inheritProperties(BaseConfig baseConfig) {
	        throwIfConfigured();

	        // Inherit forward properties
	        Properties baseProperties = baseConfig.getProperties();
	        Enumeration keys = baseProperties.propertyNames();

	        while (keys.hasMoreElements()) {
	            String key = (String) keys.nextElement();

	            // Check if we have this property before copying it
	            String value = this.getProperty(key);

	            if (value == null) {
	                value = baseProperties.getProperty(key);
	                setProperty(key, value);
	            }
	        }
	    }
	 
	 protected Properties copyProperties() {
	        Properties copy = new Properties();

	        Enumeration keys = properties.propertyNames();

	        while (keys.hasMoreElements()) {
	            String key = (String) keys.nextElement();

	            copy.setProperty(key, properties.getProperty(key));
	        }

	        return copy;
	    }

}
